import io

from flask import jsonify, request, Blueprint, send_file, make_response
import requests
import parsel
import re
from .tools.tools import *
import pdfkit

onepage_api = Blueprint('onepage_api', __name__)
config = pdfkit.configuration(wkhtmltopdf=r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0'
}


@onepage_api.route('/', methods=['GET'])
def get_onepage():
    url = request.args.get('url')
    print(f"url: {url}")
    # 验证url
    validation_response = is_valid_url(url)

    if isinstance(validation_response, tuple):  # 检查是否返回的是 JSON 响应
        return validation_response  # 直接返回错误信息

    # 继续处理 HTTP GET 请求
    response = requests.get(url=validation_response, headers=header)  # 使用有效的 URL

    if response.status_code == 200:
        html = response.text
        selector = parsel.Selector(html)
        try:
            # 文章作者
            author_url = selector.css('.profile-href::attr(href)').get()
            print(f"作者链接: {author_url}")
            # 文章标题
            title = selector.css('#articleContentId::text').get()
            new_title = re.sub(r'[\\:*?"<>|/]', '', title).strip()
            content = selector.css('#content_views').get()
            html_data = be_html(new_title, author_url,content)

            print("html_data: 完成")
            pdf_data = pdfkit.from_string(html_data, configuration=config)


        except Exception as e:
            print(f"解析失败: {e}")
            return jsonify({'error': '解析失败'})
        else:
            print("开始返回pdf文件")
            # 返回pdf文件
            # 创建一个字节流对象来保存 PDF 数据
            pdf_stream = io.BytesIO(pdf_data)
            # 将字节流的指针重置到开头
            pdf_stream.seek(0)
            # 返回 PDF 文件给前端
            return send_file(pdf_stream, as_attachment=True, download_name=f"{new_title}.pdf", )


    else:
        print('请求失败')
    return jsonify({'data': 'get_onepage_data!'})
